# -*- coding: utf-8 -*-
"""
author:码同学 极光
date:2023-02-04
desc: 
sample: 
"""
import os
import queue
import random

import requests
from gevent._semaphore import Semaphore
from locust import HttpUser, task, TaskSet, SequentialTaskSet, events

#混合场景
from util import getcsv_listdict, get_project_path


all_locusts_spawned = Semaphore()
all_locusts_spawned.acquire() #信号量占用 红灯

@events.spawning_complete.add_listener
def on_hatch_complete(**kwargs):
    all_locusts_spawned.release() #绿灯

class Login(HttpUser):
    host = 'http://82.156.74.26:9088/pinter'
    data_list = getcsv_listdict(os.path.join(get_project_path(), "files", "user.csv"))
    queue_list = queue.Queue() #并发等待的队列
    for data in data_list:
        queue_list.put(data)

    def on_start(self):
        randomData  = self.queue_list.get()
        url = self.host + '/bank/api/login2'
        self.username=randomData['username']
        data = {"userName": randomData['username'], 'password': randomData['pwd']}
        response = requests.post(url, data=data)
        json = response.json()
        token = json["data"]
        self.token = token
        #all_locusts_spawned.wait()  # 核心等待信号量


    @task  # locust
    def buy(self):
        print(self.username,self.token)
        data = {
            'userName': self.username
        }
        url = self.host + "/bank/api/query2"
        headers = {
            # 开发提供
            'testfan-token': self.token
        }
        with self.client.get(url=url, params=data, headers=headers, catch_response=True, timeout=5) as response:
            # if response.json()['message'] == 'success':
            if response.json().get('message') == 'success':
                response.success()
            else:
                response.failure(response.json())



if __name__ == '__main__':
    os.system('locust -f Login生命周期函数.py')
